package com.bjbn.service;

import com.bjbn.dto.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientRequestException;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;

/**
 * WebAPI服务类
 *
 * @author bjbn
 */
@Service
public class Webapi4IotService {

    @Autowired
    @Qualifier("httpWebClient")
    private WebClient httpWebClient;

    private final String xHwId = "jichang_io.internet.of.things_IOT";

    private final String xHwAppkey = "IOT@V$R.60ybzCI/.E3#j32$6zvOJIR$%-7@ydW9XM87n5CH7Zr=q6UrWwXUd$Bv";

    private final String appkey = "lMwyD5CQ309";

    private final String appsecret = "cPmsuivqOa";

    private final String SYSTEM_NAME = "DTS";

    /**
     * 转发API请求（HTTP）
     *
     * @param endpoint    API端点
     * @param version     api版本号
     * @param requestBody 请求体
     * @return 响应结果
     */
    private Mono<Map<String, Object>> forwardHttpApiRequest(String endpoint, String version, Object requestBody) {
        // 请求id {请求方系统缩略语}-{时间字符串}-{UUID前8位}
        String requestId = SYSTEM_NAME + "-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "-" + UUID.randomUUID().toString().substring(0, 8);

        return httpWebClient.post()
                .uri(endpoint)
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("Content-Type", "application/json")
                .header("appkey", appkey)
                .header("appsecret", appsecret)
                .header("timestamp", String.valueOf(System.currentTimeMillis()))
                .header("version", version)
                .header("requestId", requestId)
                .bodyValue(requestBody)
                .retrieve()
                // 关键修复：保留后端原始错误响应
                .onStatus(status -> status.is4xxClientError() || status.is5xxServerError(),
                        response -> response.bodyToMono(String.class)
                                .flatMap(errorBody -> {
                                    String errorMsg = String.format(
                                            "API调用失败: [状态码=%s] [requestId=%s] [URL=%s] [响应体=%s]",
                                            response.statusCode(), requestId, endpoint, errorBody
                                    );
                                    System.err.println(errorMsg);
                                    // 抛出异常，让上游处理或返回500
                                    return Mono.error(new RuntimeException(errorMsg));
                                })
                )
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                // 只处理网络异常等底层错误，不处理HTTP业务错误
                .onErrorResume(WebClientRequestException.class, e -> {
                    String errorMsg = String.format(
                            "网络异常: [requestId=%s] [URL=%s] [错误=%s]",
                            requestId, endpoint, e.getMessage()
                    );
                    System.err.println(errorMsg);
                    return Mono.error(new RuntimeException(errorMsg));
                });
    }

    public Mono<Map<String, Object>> forwardHttpApiRequestWithMasterkey(String endpoint, String version, String apiKey, Object requestBody) {
        String requestId = SYSTEM_NAME + "-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "-" + UUID.randomUUID().toString().substring(0, 8);

        return httpWebClient.post()
                .uri(endpoint)
                .header("X-HW-ID", xHwId)
                .header("X-HW-APPKEY", xHwAppkey)
                .header("Content-Type", "application/json")
                .header("appkey", appkey)
                .header("appsecret", appsecret)
                .header("timestamp", String.valueOf(System.currentTimeMillis()))
                .header("version", version)
                .header("requestId", requestId)
                .header("masterkey", apiKey)
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(Map.class)
                .cast(Map.class)
                .map(map -> (Map<String, Object>) map)
                .onErrorResume(e -> {
                    // 记录错误日志
                    System.err.println("HTTP API转发失败: " + endpoint + ", 错误: " + e.getMessage());
                    return Mono.empty();
                });
    }

    // ==================== 物联网平台API ====================

    /**
     * 查询数据上报内容
     *
     * @param request 查询请求
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getIotData(IotDataRequest request) {
        String version = "20230203093950";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        return forwardHttpApiRequest("/CAN/IOT/internetOfThings/V1/data/getDatas", version, request);
    }

    /**
     * 发送指令
     *
     * @param request 指令请求
     * @return 响应结果
     */
    public Mono<Map<String, Object>> sendIotCommand(IotCommandRequest request) {
        String version = "20230705181811";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        return forwardHttpApiRequest("/CAN/IOT/internetOfThings/V1/command/sendCommand", version, request);
    }

    /**
     * 群组指令下发
     *
     * @param request 群组指令请求
     * @return 响应结果
     */
    public Mono<Map<String, Object>> sendGroupCommand(IotGroupCommandRequest request) {
        String version = "20230705182940";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        return forwardHttpApiRequest("/CAN/IOT/internetOfThings/V1/command/sendGroupCommand", version, request);
    }

    /**
     * 取消指令
     *
     * @param request 取消指令请求
     * @return 响应结果
     */
    public Mono<Map<String, Object>> cancelCommand(IotCancelCommandRequest request) {
        String version = "20230705181746";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        return forwardHttpApiRequest("/CAN/IOT/internetOfThings/V1/command/cancelCommand", version, request);
    }

    /**
     * 查询指令下发列表
     *
     * @param request 查询指令列表请求
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getCommands(IotCommandListRequest request) {
        String version = "20230705181740";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        return forwardHttpApiRequest("/CAN/IOT/internetOfThings/V1/command/getCommands", version, request);
    }

    /**
     * 查询指令详情
     *
     * @param request 查询指令详情请求
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getCommand(IotCommandDetailRequest request) {
        String version = "20230705181736";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        return forwardHttpApiRequest("/CAN/IOT/internetOfThings/V1/command/getCommand", version, request);
    }

    /**
     * 分页查询设备列表
     *
     * @param request 查询设备列表请求
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getDeviceList(IotDeviceListRequest request) {
        String version = "20250915135221";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        return forwardHttpApiRequestWithMasterkey("/CAN/IOT/internetOfThings/V1/device/device/list", version, request.getMasterKey(), request);
    }

    /**
     * 查询设备详细信息
     *
     * @param request 查询设备详情请求
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getDeviceDetail(IotDeviceDetailRequest request) {
        String version = "20230119115348";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        return forwardHttpApiRequestWithMasterkey("/CAN/IOT/internetOfThings/V1/device/device/detail", version,request.getMasterKey(), request);
    }

    /**
     * 设备档案查询
     *
     * @param request 设备档案查询请求
     * @return 响应结果
     */
    public Mono<Map<String, Object>> getDeviceArchives(IotDeviceArchivesRequest request) {
        String version = "20230224182603";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        return forwardHttpApiRequest("/CAN/IOT/internetOfThings/V1/device_archives_mgr/getArchives", version, request);
    }

    /**
     * 查询产品信息
     *
     * @param request
     * @return
     */
    public Mono<Map<String, Object>> getIotProductDetail(IotProductDetailRequest request) {
        String version = "20230119115312";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        return forwardHttpApiRequest("/CAN/IOT/internetOfThings/V1/product/detail", version, request);
    }

    /**
     * 分页查询产品信息列表
     *
     * @param request
     * @return
     */
    public Mono<Map<String, Object>> getIotProductList(IotProductListRequest request) {
        String version = "20230119115305";
        if (!StringUtils.isEmpty(request.getApiVersion())) {
            version = request.getApiVersion();
        }
        System.out.println("version:" + version);
        return forwardHttpApiRequest("/CAN/IOT/internetOfThings/V1/product/v1/list", version, request);
    }

} 